package com.tjsinfo.tjsoa.chuanyue.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.util.MessageResources;
import org.jbpm.taskmgmt.exe.TaskInstance;
import org.json.JSONArray;
import org.json.JSONObject;

import com.tjsinfo.tjsoa.chuanyue.bo.ITChuanyueFujianBO;
import com.tjsinfo.tjsoa.chuanyue.bo.ITChuanyueNeirongBO;
import com.tjsinfo.tjsoa.chuanyue.vo.TChuanyueFujian;
import com.tjsinfo.tjsoa.chuanyue.vo.TChuanyueNeirong;
import com.tjsinfo.tjsoa.common.DealString;
import com.tjsinfo.tjsoa.common.PaginationSupport;
import com.tjsinfo.tjsoa.common.SessionUser;
import com.tjsinfo.tjsoa.common.ToolKit;
import com.tjsinfo.tjsoa.system.bo.ISystemUserBo;
import com.tjsinfo.tjsoa.system.vo.Files;
import com.tjsinfo.tjsoa.system.vo.TSystemUser;
import com.tjsinfo.tjsoa.workflow.Taskinstance;
import com.tjsinfo.tjsoa.workflow.WorkFlowTemplate;
import com.tjsinfo.tjsoa.workflow.bo.ITaskInstanceBO;
public class ShenPiAction extends DispatchAction{
	private ITChuanyueNeirongBO neirongBO;
	private ITChuanyueFujianBO fujianBO;
	private ISystemUserBo systemUserBo;
	
	private ITaskInstanceBO taskInstanceBO;
	
	public ITaskInstanceBO getTaskInstanceBO() {
		return taskInstanceBO;
	}
	public void setTaskInstanceBO(ITaskInstanceBO taskInstanceBO) {
		this.taskInstanceBO = taskInstanceBO;
	}


	public ITChuanyueNeirongBO getNeirongBO() {
		return neirongBO;
	}

	public void setNeirongBO(ITChuanyueNeirongBO neirongBO) {
		this.neirongBO = neirongBO;
	}
	
	/**
	 * 申请
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward shenqing(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		MessageResources message=getResources(arg2);
		//提交上传附件
		String fromFilePath=message.getMessage(arg2.getLocale(), "system.uploadFile.tempFilePath");
		String toFilePath = ToolKit.getProperties("com/tjsinfo/tjsoa/chuanyue/properties/systemResource.properties", this).getProperty("chuanyue.fileurl");
		List<Files> fileList=DealString.fileCopyTofile(arg2, fromFilePath, toFilePath);
		String zhusongid = arg2.getParameter("shenpirenid");
		List<String> fenfalist = new ArrayList<String>();
		String[] zhusongarray = zhusongid.split(",");
		for (int i = 0; i < zhusongarray.length; i++) {
			if (zhusongarray[i] !=null &&!"".equals(zhusongarray[i])) {
				fenfalist.add(zhusongarray[i]);
			}
		}
		WorkFlowTemplate workFlowTemplate = new WorkFlowTemplate();
		Long flowid =   workFlowTemplate.creatProcessInstance("传阅",fenfalist , "传阅",null);
		TChuanyueNeirong neirong = new TChuanyueNeirong();
		neirong.setBiaoti(arg2.getParameter("biaoti"));
		neirong.setCreatdatetime(new Date());
		neirong.setFlowid(flowid.intValue());
		neirong.setNeirong(arg2.getParameter("neirong"));
		String id =  neirongBO.addValue(neirong,fileList);
		addJingShouRen(arg2, id);
		arg2.setAttribute("linkurl", "/chuanyue/daibanlist.jsp");
		arg2.setAttribute("message", "com.tjsinfo.tjsoa.chuanyue.message");
		return arg0.findForward("success");
	}
	
	/**
	 * 待办
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward daiban(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		WorkFlowTemplate workFlowTemplate = new WorkFlowTemplate();
		String path = arg2.getContextPath();
		String basePath = arg2.getScheme()+"://"+arg2.getServerName()+":"+arg2.getServerPort()+path+"/";
		List list2 = new ArrayList();
		JSONArray array = new JSONArray();
		List list = workFlowTemplate.selectTask(SessionUser.getUserId(arg2).toString(), "传阅");
		 Comparator comp = new Comparator(){
	          public int compare(Object o1,Object o2) {
	              TaskInstance p1=(TaskInstance)o1;
	              TaskInstance p2=(TaskInstance)o2; 
	             if(p1.getId()<p2.getId())
	                 return 1;
	             else
	                 return 0;
	             }
	        };
	        Collections.sort(list, comp);
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			TaskInstance taskInstance = (TaskInstance) iterator.next();
			Long flowid =	taskInstance.getProcessInstance().getId();
			TChuanyueNeirong neirong = new TChuanyueNeirong();
			neirong.setFlowid(Integer.parseInt(flowid.toString()));
			if(neirongBO.findByExample(neirong).size() >0)
			{
				neirong = (TChuanyueNeirong)neirongBO.findByExample(neirong).get(0);
				neirong.setTaskId(taskInstance.getId());
				JSONObject object = new JSONObject();
				object.put("biaoti", neirong.getBiaoti());
				object.put("createtime", ToolKit.FormatDate(neirong.getCreatdatetime()));
				object.put("operate", "<a href='"+basePath+"tjsinfo/tjsoa/chuanyue/shenpi.do?method=kongzhi&id="+neirong.getId()+"&taskid="+neirong.getTaskId()+"'>批示</a>");
				array.put(object);
			}
		}
		arg3.getWriter().print(array);
		return  null;
	}
	
	/**
	 * 控制
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward kongzhi(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		WorkFlowTemplate workFlowTemplate = new WorkFlowTemplate();
		TChuanyueNeirong  neirong =  neirongBO.selectById(arg2.getParameter("id"));
		arg2.setAttribute("neirong", neirong);
		Long id = Long.valueOf(arg2.getParameter("taskid"));
		arg2.setAttribute("taskid", id);
		TaskInstance taskInstance   = workFlowTemplate.nextStep(id);
		if (taskInstance.getDescription().equals("传阅")) {
			addJingShouRen(arg2, neirong.getId());
			workFlowTemplate.nextStep(Long.valueOf(id),null);
			selectTask(arg2, workFlowTemplate, neirong);
			return arg0.findForward("chuanyue");
		}
		return arg0.findForward("success");
	}
	
	
	
	
	
	
	
	/**
	 * 办理
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward banli(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		WorkFlowTemplate workFlowTemplate = new WorkFlowTemplate();
		String taskid = arg2.getParameter("taskid");
		addJingShouRen(arg2, arg2.getParameter("id"));
		workFlowTemplate.nextStep(Long.valueOf(taskid),null); 
		arg2.setAttribute("linkurl", "/chuanyue/daibanlist.jsp");
		arg2.setAttribute("message", "com.tjsinfo.tjsoa.chuanyue.message");
		return arg0.findForward("success");
	}
	
	/**
	 * 跟踪
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward genzong(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		WorkFlowTemplate workFlowTemplate = new WorkFlowTemplate();
		Long flowid = Long.valueOf(arg2.getParameter("flowid"));
		Integer unfinshtasksize  = workFlowTemplate.selectunfinishedTasksSize(flowid);
		PaginationSupport paginationSupport = null;
		List<Taskinstance> list;
		JSONArray array = new JSONArray();
		JSONObject object = new JSONObject();
		if (arg2.getParameter("start") == null) {
			paginationSupport =  taskInstanceBO.genZong(flowid, 0, 23);
		} else {
			Integer first = Integer.parseInt(arg2.getParameter("start"));
			paginationSupport = taskInstanceBO.genZong(flowid, first, 23);
		}
		Integer totalProperty = paginationSupport.getTotalCount();
		object.put("totalProperty", totalProperty);
		list = paginationSupport.getItems();
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Taskinstance taskinstance = (Taskinstance) iterator.next();
			JSONObject taskObject = new JSONObject();
			taskObject.put("taskname", taskinstance.getName());
			taskObject.put("username", taskinstance.getTjsUser().getUserName());
			taskObject.put("time", ToolKit.getFormatDate(taskinstance.getEnd(), "yyyy-MM-dd HH:mm"));
			if(taskinstance.getEnd() ==null && unfinshtasksize > 1)
			{
				taskObject.put("operate", "<a href='javascript:selectuserradiowinshow("+taskinstance.getId()+",userid,username,node)'>修改候选人</a>&nbsp;&nbsp;<a href='javascript:endTask("+taskinstance.getId()+")'>结束</a>");
			}
			else if(taskinstance.getEnd() ==null)
			{
				taskObject.put("operate", "<a href='javascript:selectuserradiowinshow("+taskinstance.getId()+",userid,username,node)'>修改候选人</a>");
			}
			else
			{
				taskObject.put("operate", "");
			}
			array.put(taskObject);
		}
		object.put("root", array);
		arg3.getWriter().print(object);
		return null;
	}
	
	/**
	 * 只读查询
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward selectonedoc(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		WorkFlowTemplate workFlowTemplate = new WorkFlowTemplate();
		TChuanyueNeirong neirong = neirongBO.selectById(arg2.getParameter("id"));
		arg2.setAttribute("neirong", neirong);
		selectTask(arg2, workFlowTemplate, neirong);
		return arg0.findForward("selectonedoc");
		
		
	}
	/**
	 * 添加经手人

	 * @param request
	 * @param docid
	 */
	private void addJingShouRen(HttpServletRequest request, String docid) {
		TChuanyueNeirong neirong;
		neirong = neirongBO.selectById(docid);
		if(neirong.getJingshouren() == null)
		{
			neirong.setJingshouren(","+SessionUser.getUser(request).getUser_id()+",");
			neirong.setJingshoubumen(SessionUser.getUser(request).getDepartment());
		}
		else
		{
			neirong.setJingshouren(neirong.getJingshouren()+SessionUser.getUser(request).getUser_id()+",");
			neirong.setJingshoubumen(neirong.getJingshoubumen()+SessionUser.getUser(request).getDepartment()+",");
		}
		neirongBO.updateValue(neirong);
	}
	
	/**
	 * 下载
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward download(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		String url = "error";
		// TODO Auto-generated method stub
		try {
			String id=arg2.getParameter("id");
			TChuanyueFujian	 fujian = fujianBO.selectByOne(id);
			File file = new File(fujian.getFujianAddress()); 			
			String filename = file.getName();
			InputStream fis = new BufferedInputStream(new FileInputStream(fujian.getFujianAddress()));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();		
			arg3.reset();
			arg3.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
			arg3.addHeader("Content-Length", "" + file.length());
	        OutputStream toClient = new BufferedOutputStream(arg3.getOutputStream());
	        arg3.setContentType("application/octet-stream");
	        toClient.write(buffer);
	        toClient.flush();
	        toClient.close();
			url = "ok";
		} catch (IOException ex) {
			arg2.setAttribute("returnSting", "服务器忙，请稍后下载！");
			ex.printStackTrace();
			return arg0.findForward("error");
		} catch(NullPointerException ex){
			return null;
		} catch (Exception ex){
			arg2.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return arg0.findForward("error");
		}
		if ("ok".equals(url)) {
			return null;	
		}else {
			arg2.setAttribute("returnSting", "服务器忙，请稍后下载！");
			return  arg0.findForward(url);
		}
	}
	
	/**
	 * 中止一个流程

	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward suspend(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		WorkFlowTemplate workFlowTemplate = new WorkFlowTemplate();
		Long flowid = Long.valueOf(arg2.getParameter("flowid"));
		   if (workFlowTemplate.processInstanceSuspend(flowid)) {
		    	JSONObject object = new JSONObject();
		    	object.put("success", true);
		    	arg3.getWriter().print(object);
			} else {
				JSONObject object = new JSONObject();
		    	object.put("success", false);
		    	arg3.getWriter().print(object);
			}
		return null;
	}
	
	
	/**
	 * 重启一个流程

	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward resume(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		WorkFlowTemplate workFlowTemplate = new WorkFlowTemplate();
		Long flowid = Long.valueOf(arg2.getParameter("flowid"));
		   if (workFlowTemplate.processInstanceResume(flowid)) {
		    	JSONObject object = new JSONObject();
		    	object.put("success", true);
		    	arg3.getWriter().print(object);
			} else {
				JSONObject object = new JSONObject();
		    	object.put("success", false);
		    	arg3.getWriter().print(object);
			}
		return null;
	}
	/**
	 * 改变任务接收人

	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward changActor(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		WorkFlowTemplate workFlowTemplate = new WorkFlowTemplate();
		Long taskid = Long.valueOf(arg2.getParameter("taskid"));
		String actorid = arg2.getParameter("actorid");
		if (workFlowTemplate.changTaskActor(taskid,actorid)) {
			JSONObject object = new JSONObject();
	    	object.put("success", true);
	    	arg3.getWriter().print(object);
		} else {
			JSONObject object = new JSONObject();
	    	object.put("success", false);
	    	arg3.getWriter().print(object);
		}				 
		return null;
	}
	/**
	 * 删除任务
	 * @param arg0
	 * @param arg1
	 * @param arg2
	 * @param arg3
	 * @return
	 * @throws Exception
	 */
	public ActionForward deleteTask(ActionMapping arg0, ActionForm arg1,
			HttpServletRequest arg2, HttpServletResponse arg3) throws Exception {
		// TODO Auto-generated method stub
		WorkFlowTemplate workFlowTemplate = new WorkFlowTemplate();
		Long taskid = Long.valueOf(arg2.getParameter("taskid"));
		if (neirongBO.deleteTask(taskid.intValue())) {
			JSONObject object = new JSONObject();
	    	object.put("success", true);
	    	arg3.getWriter().print(object);
		} else {
			JSONObject object = new JSONObject();
	    	object.put("success", false);
	    	arg3.getWriter().print(object);
		}				 
		return null;
	}
	/**
	 * 查询已阅人和未阅人

	 * @param arg2
	 * @param workFlowTemplate
	 * @param neirong
	 */
	private void selectTask(HttpServletRequest arg2,
			WorkFlowTemplate workFlowTemplate, TChuanyueNeirong neirong) {
		List<String> alltaskid = new ArrayList<String>();
		Collection<TaskInstance> alltask =  workFlowTemplate.selectAllTasks(Long.valueOf(neirong.getFlowid().toString()));
		for (TaskInstance taskInstance2 : alltask) {
			alltaskid.add(taskInstance2.getActorId());
		}
		Collection<TaskInstance> unfinshtask =  workFlowTemplate.selectunfinishedTasks(Long.valueOf(neirong.getFlowid().toString()));
		List<String> unfinshtaskid = new ArrayList<String>();
		for (TaskInstance taskInstance3 : unfinshtask) {
			unfinshtaskid.add(taskInstance3.getActorId());
		}
		alltaskid.removeAll(unfinshtaskid);
		List<String> taskusernamelist = new ArrayList<String>();
		List<String> unfinshtaskusernamelist = new ArrayList<String>();
		for (String userid : alltaskid) {
			TSystemUser user = systemUserBo.findByIdSystemUser(Integer.parseInt(userid));
			taskusernamelist.add(user.getUserName());
		}
		for (String userid : unfinshtaskid) {
			TSystemUser user = systemUserBo.findByIdSystemUser(Integer.parseInt(userid));
			unfinshtaskusernamelist.add(user.getUserName());
		}
		arg2.setAttribute("taskusernamelist", taskusernamelist);
		arg2.setAttribute("unfinshtaskusernamelist", unfinshtaskusernamelist);
	}
	
	public ITChuanyueFujianBO getFujianBO() {
		return fujianBO;
	}
	public void setFujianBO(ITChuanyueFujianBO fujianBO) {
		this.fujianBO = fujianBO;
	}
	public ISystemUserBo getSystemUserBo() {
		return systemUserBo;
	}
	public void setSystemUserBo(ISystemUserBo systemUserBo) {
		this.systemUserBo = systemUserBo;
	}
}
